package com.yungu.swift.order.utils;

import com.yungu.swift.utils.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author : cuixiuyin
 * @date : 2019/4/8
 */
public class XmlUtils {

    private static Logger logger = LoggerFactory.getLogger(XmlUtils.class);

    private XmlUtils() {

    }

    public static String buildXml(Map<String, String> map) {
        StringBuilder sb = new StringBuilder("<xml>");
        for (String key : map.keySet()) {
            String value = map.get(key);
            if (StringUtils.isNotEmpty(value)) {
                sb.append("<").append(key).append(">").append(value).append("</").append(key).append(">");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }

    public static Map<String, String> readValueAsMap(String xml) {
        Map<String, String> map = new HashMap<>(64);
        try {
            //将字符串转为XML
            Document doc = DocumentHelper.parseText(xml);
            //获取根节点
            Element rootElt = doc.getRootElement();
            //遍历节点
            Iterator iterator = rootElt.elementIterator();
            while (iterator.hasNext()) {
                Element element = (Element) iterator.next();
                map.put(element.getName(), element.getText());
            }
        } catch (Exception e) {
            logger.error("XmlUtils readValueAsMap Exception,xml:{}", xml, e);
        }
        return map;
    }
}
